<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="课程名称">
          <n-input v-model:value="search_param.name" placeholder="请输入课程名称查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item label="年级">
          <n-select v-model:value="search_param.gId" :options="gradeOption" value-field="key" style="width: 130px;"
                    placeholder="请选择年级" clearable/>
        </n-form-item>
        <n-form-item label="分类">
          <n-select v-model:value="search_param.cId" :options="catOption" value-field="key" style="width: 130px;"
                    placeholder="请选择分类" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.name=null,search_param.status=null,search_param.gId=null,search_param.cId=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="course/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['course:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--新增、修改课程-->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改课程':'新增课程'" :mask-closable="false"
             :show-icon="false" preset="dialog" @after-leave="closeAddEditModel" style="width: 1060px">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              :label-width="80" label-placement="left">
        <n-tabs type="line">
          <n-tab-pane name="basic" tab="基本">
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="课程名称" path="name">
                <n-input v-model:value="addEditForm.name" placeholder="请填写课程名称" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="12" label="所属分类" path="cId">
                <n-select v-model:value="addEditForm.cId" :options="catOption" value-field="key"
                          placeholder="请选择课程所属分类" clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="所属年级" path="gradeId">
                <n-select v-model:value="addEditForm.gradeId" :options="gradeOption" value-field="key"
                          placeholder="请选择课程所属年级" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="封面" path="cover">
                <image-selection v-model:value="addEditForm.cover"/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="8" label="每一课时" path="classHour">
                <n-input-group>
                  <n-input-number v-model:value="addEditForm.classHour" :precision="0" :min="0" :max="120"
                                  :show-button="false" placeholder="请填写每课时 如:45分钟" clearable/>
                  <n-input-group-label>分钟</n-input-group-label>
                </n-input-group>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="最低价" path="minPrice">
                <n-input-group>
                  <n-input-number v-model:value="addEditForm.minPrice" :precision="2" :min="0" :show-button="false"
                                  placeholder="请填写最低价" clearable/>
                  <n-input-group-label>元/每课时</n-input-group-label>
                </n-input-group>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="最高价" path="maxPrice">
                <n-input-group>
                  <n-input-number v-model:value="addEditForm.maxPrice" :precision="2" :min="0" :show-button="false"
                                  placeholder="请填写最高价" clearable/>
                  <n-input-group-label>元/每课时</n-input-group-label>
                </n-input-group>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="8" label="排序" path="sort">
                <n-input-number v-model:value="addEditForm.sort" :show-button="false" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="8" label="状态" path="status" :show-feedback="false">
                <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="1" :unchecked-value="0">
                  <template #checked>
                    正常
                  </template>
                  <template #unchecked>
                    停用
                  </template>
                </n-switch>
              </n-form-item-gi>
            </n-grid>
          </n-tab-pane>
          <n-tab-pane name="details_editor" tab="详情">
            <n-form-item path="details">
              <div style="height: 380px">
                <editor v-model:value="addEditForm.details" mode="simple"/>
              </div>
            </n-form-item>
          </n-tab-pane>
        </n-tabs>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>
<script setup lang="ts">
import {ref, onMounted, h, reactive} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {NImage, NPopconfirm, NTag, SelectOption, useMessage, FormInst} from "naive-ui";

import {delRequest, postPutRequest, getRequest} from "@/api/data.ts";

import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {AddSharp} from "@vicons/material";

import Editor from '@components/Editor'

import {imagePreview} from '@/util';
import ImageSelection from "@components/ImageSelection";

const message = useMessage()


const statusOption = ref<SelectOption[]>([
  {
    label: '启用',
    value: 1,
  }, {
    label: '停用',
    value: 0,
  }
]);
const gradeOption = ref<SelectOption[]>([]);//年级
const catOption = ref<SelectOption[]>([]);//年级
const search_param = ref({
  name: null,
  gId: null,
  cId: null,
  status: null
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '名称',
    key: 'name',
  }, {
    title: '课程封面',
    key: 'cover',
    width: 100,
    align: 'center',
    render(row: { cover: string }) {
      if (row.cover) {
        return h(NImage, {
          width: 20,
          height: 20,
          src: imagePreview(row.cover)
        })
      }
    }
  }, {
    title: '分类',
    key: 'classifyName',
    width: 110,
    align: 'center',
  }, {
    title: '年级',
    key: 'gradeName',
    width: 110,
    align: 'center',
  }, {
    title: '每一课时(分钟)',
    key: 'classHour',
    width: 130,
    align: 'center',
  }, {
    title: '价格(元)',
    key: 'classHour',
    width: 130,
    align: 'center',
    render(row: { minPrice: number, maxPrice: number }) {
      return h('span', null, {default: () => (row.minPrice?.toFixed(2) + '-' + row.maxPrice?.toFixed(2))});
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_color = row.status ? 'success' : 'warning';
      const enabled_text = row.status ? '正常' : '停用';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '排序',
    key: 'sort',
    width: 100,
    align: 'center'
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  },
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['course:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前课程吗？',
          },
          permission: ['course:edit']
        },
      ]
    });
  },
});
//新增、修改课程
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  name: '',
  cId: null,
  gradeId: null,
  cover: null,
  classHour: null,
  minPrice: null,
  maxPrice: null,
  status: 1,
  sort: 100,
  details: '',
})
const addEditFormRules = ref({
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写分类'
  },
  cId: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择所属分类'
  },
  gradeId: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择所属年级'
  },
  classHour: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写每课时'
  },
  minPrice: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写最低价'
  },
  maxPrice: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写最高价'
  },
  cover: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择课程封面'
  },
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.name = record.name;
  addEditForm.value.cId = record.cid;
  addEditForm.value.gradeId = record.gradeId;
  addEditForm.value.cover = record.cover;
  addEditForm.value.classHour = record.classHour;
  addEditForm.value.minPrice = record.minPrice;
  addEditForm.value.maxPrice = record.maxPrice;
  addEditForm.value.status = record.status;
  addEditForm.value.sort = record.sort;
  addEditForm.value.details = record.details;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('course/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}

const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.name = '';
  addEditForm.value.cId = null;
  addEditForm.value.gradeId = null;
  addEditForm.value.cover = null;
  addEditForm.value.classHour = null;
  addEditForm.value.minPrice = null;
  addEditForm.value.maxPrice = null;
  addEditForm.value.status = 1;
  addEditForm.value.sort = 100;
  addEditForm.value.details = '';
  handelSubmitLoading.value = false;
}
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'course/edit' : 'course/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
const getGrade = async () => {
  await getRequest("grade/select").then((result: ResponseResult) => {
    const {data} = result;
    gradeOption.value = data;
  })
}
const getCat = async () => {
  await getRequest("classify/select").then((result: ResponseResult) => {
    const {data} = result;
    catOption.value = data;
  })
}
onMounted(() => {
  getGrade();
  getCat();
})


</script>
<style scoped lang="scss">

</style>